/* 
 * Copyright (C) 2014 Ningbo Yuanqun Inc., All Rights Reserved. 
 */
package com.yuanqunsoft.alimigration.engine.rule.factory;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.yuanqunsoft.alimigration.common.GlobalConfig;
import com.yuanqunsoft.alimigration.common.PropertiesUtil;
import com.yuanqunsoft.alimigration.engine.RuleParser;
import com.yuanqunsoft.alimigration.engine.vo.RuleImpl;

public class RuleParserFactory {

    private static Logger logger = LogManager.getLogger(RuleParserFactory.class);

    private static String packagePrefix;

    private URLClassLoader loader = null;

    static {
        packagePrefix = PropertiesUtil.getProperty(GlobalConfig.ENGINE_PROPERTIES_PACKAGE_PATH);
    }

    /**
     * <p>
     * 根据 <code>ruleImpl</code> 和 <code>engineType</code> 创造对应的规则解析实现类
     * </p>
     * 
     * @param ruleImpl
     *            规则实现的映射
     * @param engineType
     *            引擎的类型
     * @return
     */
    public RuleParser createRuleParser(RuleImpl ruleImpl) {
        String className = (packagePrefix + "." + ruleImpl.getEngineType()).toLowerCase() + "."
                + ruleImpl.getImplClassName();
        Class<?> parserClass = null;
        try {
            loader = new URLClassLoader(new URL[] { PropertiesUtil.getRuleImplClassBasedDir().toURI().toURL() },
                    getClass().getClassLoader());
            parserClass = loader.loadClass(className);
        } catch (ClassNotFoundException | MalformedURLException e) {
            logger.error(e);
            e.printStackTrace();
        }
        RuleParser parser = null;
        try {
            parser = (RuleParser) parserClass.newInstance();
            parser.initRuleParser(ruleImpl);
        } catch (InstantiationException e) {
            logger.error(e);
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            logger.error(e);
            e.printStackTrace();
        }
        return parser;
    }

    @Override
    protected void finalize() throws Throwable {
        // TODO Auto-generated method stub
        if (loader != null) {
            try {
                loader.close();
            } catch (IOException e) {
                logger.error(e);
                e.printStackTrace();
            }
        }
        super.finalize();
    }
}
